package cn.player.download;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;

import java.util.ArrayList;
import java.util.List;

import cn.player.AIDLDownloadClient;
import cn.player.AIDLDownloadService;
import cntv.player.core.util.LogUtil;


public class FileDownloadService extends Service implements DownloadFileTask.DownloadTaskCallback {
	private AIDLDownloadClient mClientIMPL;
	private DownloadThreadPool mThreadPool;
	private boolean mWorkActive = true;

	class ServiceIMPL extends AIDLDownloadService.Stub {

		@Override
		public void stopTask(DownloadInfo entity) throws RemoteException {
		}

		@Override
		public void setClientIMPL(AIDLDownloadClient aidlClient)throws RemoteException {
			mClientIMPL = aidlClient;
		}

		@Override
		public List<DownloadInfo> getAllTask() throws RemoteException {
			List<DownloadInfo> allTaskInDb = getAllTaskInDb();
			return allTaskInDb;
		}

		@Override
		public int addNewTask(DownloadInfo entity, int priority) throws RemoteException {
			return onNewTask(entity,priority);
		}

		@Override
		public void startTask(DownloadInfo entity) throws RemoteException {
			onNewTask(entity);
		}

		@Override
		public AIDLDownloadClient getClientIMPL() throws RemoteException {
			return mClientIMPL;
		}

		@Override
		public void deleteTask(DownloadInfo entity) throws RemoteException {

		}
	}

    /**
     * 尝试启动新的下载任务
     *
     * @param entity
     * @return
     */
    private int onNewTask(DownloadInfo entity) {
        mThreadPool.execute(new DownloadFileTask(this, entity, this));
        return DownloadThreadPool.DOWNLOAD_START_SUCCESS;
    }

    private int onNewTask(DownloadInfo entity, int priority) {
        mThreadPool.execute(new DownloadFileTask(this, entity, priority, this));
        return DownloadThreadPool.DOWNLOAD_START_SUCCESS;
    }

	@Override
	public void onCreate() {
		super.onCreate();
	}


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        LogUtil.u("service onStartCommand");

        mThreadPool = DownloadThreadPool.getInstance();
        return super.onStartCommand(intent, flags, startId);
    }

	/**
	 * 返回数据库里未完成的所有任务entity。
	 */
	private List<DownloadInfo> getTaskInDb() {
		List<DownloadInfo> all = null;
		/*try {
			// 准备阶段和正在下载阶段,以及暂停和出错阶段的任务可以重新下载
			all = mDbUtils.findAll(Selector.from(DownloadInfo.class).where(
					"downloadState", "<=", DownloadInfo.DOWNLOAD_ERR));
		} catch (DbException e) {
			e.printStackTrace();
		}*/
		return null != all ? all : new ArrayList<DownloadInfo>();
	}

	/**
	 * 返回数据库里所有任务entity。
	 */
	private List<DownloadInfo> getAllTaskInDb() {
		List<DownloadInfo> all = null;
		/*try {
			all = mDbUtils.findAllA(Selector.from(DownloadInfo.class).where(
					"downloadState", "!=", DownloadInfo.DOWNLOAD_NOT_EXISTS));
		} catch (DbException e) {
			e.printStackTrace();
		}*/
		return null != all ? all : new ArrayList<DownloadInfo>();
	}


	@Override
	public IBinder onBind(Intent intent) {
		LogUtil.u("service onBind");
		return new ServiceIMPL();
	}

	@Override
	public boolean onUnbind(Intent intent) {
		LogUtil.u("service onUnBind");
		return super.onUnbind(intent);
	}

	@Override
	public void onDestroy() {
		LogUtil.u("service onDestroy");
//		unregisterReceiver(mNetTypeConnectReceiver);
		super.onDestroy();
	}


    @Override
    public void onDownloadStarted(DownloadInfo entity) {
        try {
            if (mClientIMPL != null) {
                mClientIMPL.onTaskStart(entity);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDownloadUpdate(DownloadInfo entity) {
        try {
            if (mClientIMPL != null) {
                mClientIMPL.onTaskUpdate(entity);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void onDownloadCompleted(DownloadInfo entity) {
        try {
            if (mClientIMPL != null) {
                mClientIMPL.onTaskComplete(entity);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDownloadPaused(DownloadInfo entity) {
        try {
            if (mClientIMPL != null) {
                mClientIMPL.onTaskPaused(entity);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDownloadCanceled(DownloadInfo entity) {
        try {
            if (mClientIMPL != null) {
                mClientIMPL.onTaskCanceled(entity);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onDownloadFailed(DownloadInfo entity, Throwable ex) {
        String errInfo = ex == null ? "unknow err info" : ex.getMessage();
        try {
            if (mClientIMPL != null) {
                mClientIMPL.onTaskFailed(entity, errInfo);
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onNoTaskAlive() {
        try {
            if (mClientIMPL != null) {
                mClientIMPL.onNoTasks();
            } else {
                stopSelf();
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}
